{% set need_git = 'git' in tools_detected %}
{% set need_pkgcfg = 'pkg-config' in tools_detected %}
{% set need_cgo = use_cgo %}
{% set need_make = 'make' in tools_detected %}
{% set pname = (project_name | default('app')) %}
{% set installer_mode = (build_mode == 'project_installer') %}
{% set is_lightweight = (build_mode_name == 'lightweight') %}
{% set is_debug = (build_mode_name == 'debug') %}
{% set mode = mode_config or {} %}

ARG OCO_TAG=latest

# ==============================
# Builder Stage (OpenCloudOS 9)
# ==============================
{% if is_debug %}
FROM opencloudos/opencloudos:9.0 AS builder
{% else %}
FROM opencloudos/opencloudos9-minimal:${OCO_TAG} AS builder
{% endif %}
WORKDIR /src

# 先安装下载/解压所需的基础工具
RUN set -eux; \
    if command -v microdnf >/dev/null 2>&1; then \
        microdnf -y install tar gzip curl ca-certificates && microdnf clean all; \
    else \
        dnf -y install tar gzip curl ca-certificates && dnf clean all; \
    fi


# 可选：Go 模块代理
ENV GOPROXY=https://goproxy.cn,direct

# 设置 Go 版本
ARG GO_VERSION={{ go_version | default('1.20') }}

# 动态检查 Go 版本并下载相应的安装包
RUN set -eux; \
    # 如果 GO_VERSION 是两位数且是 1.21 或更高版本，则加上 .0 后缀
    if [[ "$GO_VERSION" =~ ^1\.[0-9]+$ ]]; then \
        minor_version=$(echo "$GO_VERSION" | cut -d '.' -f 2); \
        if [ "$minor_version" -ge 21 ]; then \
            GO_VERSION="${GO_VERSION}.0"; \
            echo "GO_VERSION updated to $GO_VERSION"; \
        fi; \
    fi; \
    echo "Downloading Go $GO_VERSION..."; \
    DOWNLOAD_URL="https://dl.google.com/go/go$GO_VERSION.linux-amd64.tar.gz"; \
    echo "Download URL: $DOWNLOAD_URL"; \
    rm -rf /usr/local/go; \
    curl -fsSL "$DOWNLOAD_URL" -o /tmp/go$GO_VERSION.linux-amd64.tar.gz; \
    if [ ! -f /tmp/go$GO_VERSION.linux-amd64.tar.gz ]; then echo "Download failed"; exit 1; fi; \
    tar -C /usr/local -xzf /tmp/go$GO_VERSION.linux-amd64.tar.gz; \
    rm /tmp/go$GO_VERSION.linux-amd64.tar.gz;

ENV PATH="/usr/local/go/bin:${PATH}"
ENV GO111MODULE=on

RUN go version

{% if installer_mode %}
# ---------- 自带安装器模式 ----------
RUN set -eux; \
    if command -v microdnf >/dev/null 2>&1; then \
        microdnf install -y make git pkgconf-pkg-config cmake curl wget unzip gcc gcc-c++ && microdnf clean all; \
    else \
        dnf -y install make git pkgconf-pkg-config cmake curl wget unzip gcc gcc-c++ && dnf clean all; \
    fi

COPY . .

{% if strip_sudo %}
RUN set -eux; \
    if [ -f Makefile ]; then sed -ri 's/\bsudo\s+//g' Makefile; fi; \
    if [ -f scripts/install.sh ]; then sed -ri 's/\bsudo\s+//g' scripts/install.sh; fi || true
{% endif %}

RUN set -eux; {{ installer_cmd }} || (echo "项目自带安装流程执行失败" && exit 1)
ENV CGO_ENABLED=1

{% else %}
# ---------- 常规模式 ----------
RUN set -eux; \
    REQUIRED_PKGS=""; \
    {% if need_cgo %} REQUIRED_PKGS="${REQUIRED_PKGS} gcc glibc-devel gcc-c++"; {% endif %} \
    {% if need_git %} REQUIRED_PKGS="${REQUIRED_PKGS} git"; {% endif %} \
    {% if need_pkgcfg %} REQUIRED_PKGS="${REQUIRED_PKGS} pkg-config"; {% endif %} \
    {% if need_make or need_git %} REQUIRED_PKGS="${REQUIRED_PKGS} make"; {% endif %} \
    {% if is_debug %} REQUIRED_PKGS="${REQUIRED_PKGS} strace gdb curl wget"; {% endif %} \
    if [ -n "$REQUIRED_PKGS" ]; then \
        if command -v microdnf >/dev/null 2>&1; then microdnf install -y $REQUIRED_PKGS && microdnf clean all; \
        else dnf -y install $REQUIRED_PKGS && dnf clean all; fi; \
    fi

COPY go.mod go.sum* ./
RUN [ -f go.mod ] && go mod download || true

COPY . .
RUN set -eux; \
    find . -name go.mod -type f -print0 | while IFS= read -r -d '' f; do \
      d="$(dirname "$f")"; echo ">>> preparing deps in $d"; \
      ( cd "$d"; go env -w GO111MODULE=on; (go get ./... || true); go mod download; (go mod tidy || true) ); \
    done

ENV CGO_ENABLED={{ 1 if need_cgo else 0 }}
{% endif %}

{% if multi_bin %}
# =============================
# 多入口编译（保留目录层级 + 正确的可执行名）
# 产物布局示例：
#   /out/bin/cmd/cmd
#   /out/bin/cmd/caddy/caddy
# =============================
RUN set -eux; \
    mkdir -p /out/bin; \
{% for b in bin_entries -%}
    mkdir -p "/out/bin/{{ b.out_rel }}"; \
{% if is_lightweight %}
    go build -C "{{ b.dir }}" -trimpath -ldflags "-s -w" -o "/out/bin/{{ b.out_rel }}/{{ b.bin_name }}" .; \
{% elif is_debug %}
    go build -C "{{ b.dir }}" -trimpath -gcflags="all=-N -l" -o "/out/bin/{{ b.out_rel }}/{{ b.bin_name }}" .; \
{% else %}
    go build -C "{{ b.dir }}" -trimpath -ldflags "-s -w" -o "/out/bin/{{ b.out_rel }}/{{ b.bin_name }}" .; \
{% endif %}
{% endfor -%}
    true

# ldd 汇总（每个可执行文件）
RUN set -eux; : > /out/ldd.txt; \
    find /out/bin -type f -executable | while read f; do \
      echo "=== $f ===" >> /out/ldd.txt; \
      ldd "$f" >> /out/ldd.txt 2>/dev/null || true; \
      echo >> /out/ldd.txt; \
    done
{% else %}
# =============================
# 单入口编译（保持旧逻辑）
# =============================
RUN set -eux; \
    d="$(dirname "{{ entry_rel }}")"; \
{% if is_lightweight %}
    go build -C "$d" -trimpath -ldflags "-s -w" -o /out/main .
{% elif is_debug %}
    go build -C "$d" -trimpath -gcflags="all=-N -l" -o /out/main .
{% else %}
    go build -C "$d" -trimpath -ldflags "-s -w" -o /out/main .
{% endif %}
RUN ldd /out/main > /out/ldd.txt 2>/dev/null || true
{% endif %}

# ==============================
# Runtime Stage (OpenCloudOS 9)
# ==============================
{% if is_lightweight %}
FROM opencloudos/opencloudos9-minimal:${OCO_TAG}
{% elif is_debug %}
FROM opencloudos/opencloudos:9.0
{% else %}
FROM opencloudos/opencloudos9-minimal:${OCO_TAG}
{% endif %}
WORKDIR /app/{{ pname }}

{% if installer_mode %}
COPY --from=builder /usr/local/ /usr/local/
ENV LD_LIBRARY_PATH="/usr/local/lib64:/usr/local/lib:${LD_LIBRARY_PATH}"
{% endif %}

# 根据构建模式安装运行时包
{% if is_lightweight %}
RUN set -eux; \
    if command -v microdnf >/dev/null 2>&1; then microdnf install -y ca-certificates && microdnf clean all; \
    else dnf -y install ca-certificates && dnf clean all; fi
{% elif is_debug %}
RUN set -eux; \
    if command -v microdnf >/dev/null 2>&1; then microdnf install -y ca-certificates tzdata curl wget strace gdb net-tools procps-ng vim-minimal less && microdnf clean all; \
    else dnf -y install ca-certificates tzdata curl wget strace gdb net-tools procps-ng vim-minimal less && dnf clean all; fi
{% else %}
{% if runtime_sys_packages and runtime_sys_packages|length > 0 %}
RUN set -eux; \
    if command -v microdnf >/dev/null 2>&1; then microdnf install -y {{ runtime_sys_packages|join(' ') }} && microdnf clean all; \
    else dnf -y install {{ runtime_sys_packages|join(' ') }} && dnf clean all; fi
{% endif %}
{% endif %}

{% if multi_bin %}
# 多工具：扁平名放到 /app/<pname>/bin/<name>
COPY --from=builder /out/bin/ /app/{{ pname }}/bin/
COPY --from=builder /out/ldd.txt /ldd.txt
{% else %}
RUN set -eux; mkdir -p "/app/{{ pname }}/bin"
COPY --from=builder /out/main /app/{{ pname }}/bin/{{ pname }}
COPY --from=builder /out/ldd.txt /ldd.txt
{% endif %}

{% if not is_lightweight %}
{% for readme in readmes %}
COPY {{ readme }} /app/{{ pname }}/
{% endfor %}

{% if has_docs %}
COPY docs/ /app/{{ pname }}/docs/
{% endif %}
{% endif %}

ENV PATH="/app/{{ pname }}/bin:${PATH}"

# 根据模式设置用户和命令
{% if is_lightweight %}
USER nobody
CMD ["/app/{{ pname }}/bin/{{ pname }}"]
{% elif is_debug %}
# 调试模式额外配置
EXPOSE 8080 9090 6060
CMD ["/bin/sh"]
{% else %}
CMD ["/bin/sh"]
{% endif %}